package kr.or.smardi.smardi_AScan.User;

import java.util.*;

import kr.or.smardi.smardi_AScan.*;
import kr.or.smardi.smardi_AScan.Help.*;
import kr.or.smardi.smardi_AScan.Record.*;
import kr.or.smardi.smardi_AScan.Scan.*;
import kr.or.smardi.smardi_AScan.db.*;
import android.app.*;
import android.content.*;
import android.database.*;
import android.graphics.*;
import android.graphics.drawable.*;
import android.os.*;
import android.text.*;
import android.util.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class AC_UserMain extends Activity {

	LinearLayout linear_userlist;
	ImageView btn_userChange, btn_userDelete, btn_userAdd;
	TextView txt_explain;

	// 상단 타이틀바
	RelativeLayout titleBar = null;
	ImageButton btn_TopLeft = null;
	ImageButton btn_TopRight = null;
	TextView txt_subTitle = null;

	// 탭 메뉴
	LinearLayout tabMenu = null;
	ImageButton tab_measure = null;
	ImageButton tab_record = null;
	ImageButton tab_user = null;
	ImageButton tab_help = null;

	int scanPoint = 0; // 1:top, 2:left, 3:right, 4:bottom
	ArrayList<Button> listPoint;
	ArrayList<TextView> listName;
	ArrayList<ArrayList<String>> listUser; // user list loaded from DB

	final int NAME_TOP = 0;
	final int NAME_MIDDLE = 1;
	final int NAME_BOTTOM = 2;

	String selectedName = "";
	int selectedNameID = -1; // 선택된 행의 아이디를 저장
	long lastClickedNameTime = 0; // 마지막으로 이름이 선택된 시간
	long doubleClickTime = 500; // 더블클릭으로 인식할 수 있는 시간 간격

	DB_Adapter dbAdapter;

	// SharedPreference
	Manage_SharedPreference mSharedPreference;

	long lastBackPressTime = 0;
	Toast toast;
	boolean isUserWantToExit = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_main);

		dbAdapter = new DB_Adapter(AC_UserMain.this);
		dbAdapter.open();

		// 타이틀바 세팅
		titleBar = (RelativeLayout) findViewById(R.id.inc_title_bar);
		btn_TopLeft = (ImageButton) titleBar.findViewById(R.id.btn_top_left);
		btn_TopLeft.setImageDrawable(getResources().getDrawable(
				R.drawable.c_btn_back));
		btn_TopLeft.setOnClickListener(onClickListener);
		btn_TopRight = (ImageButton) titleBar.findViewById(R.id.btn_top_right);
		btn_TopRight.setOnClickListener(onClickListener);
		txt_subTitle = (TextView) findViewById(R.id.txt_subTitle);
		txt_subTitle.setText(getString(R.string.subTitle_user_main));

		// 탭 세팅--------------------------
		tabMenu = (LinearLayout) findViewById(R.id.inc_tab_menu);
		tab_measure = (ImageButton) findViewById(R.id.tab_measure);
		tab_record = (ImageButton) findViewById(R.id.tab_record);
		tab_user = (ImageButton) findViewById(R.id.tab_user);
		tab_user.setImageDrawable(getResources().getDrawable(
				R.drawable.tab_user_1));
		tab_help = (ImageButton) findViewById(R.id.tab_help);

		tab_measure.setOnClickListener(onClickListener);
		tab_record.setOnClickListener(onClickListener);
		tab_help.setOnClickListener(onClickListener);
		// 탭 세팅 끝--------------------------

		txt_explain = (TextView) findViewById(R.id.txt_explain);
		txt_subTitle = (TextView) findViewById(R.id.txt_subTitle);

		btn_userDelete = (ImageView) findViewById(R.id.btn_user_delete);
		btn_userAdd = (ImageView) findViewById(R.id.btn_user_add);
		btn_userChange = (ImageView) findViewById(R.id.btn_user_change);

		mSharedPreference = new Manage_SharedPreference(AC_UserMain.this);

		makeUserList();

		registButtonEvents();
	}

	private void setExplainText() {
		txt_explain.setText(getString(R.string.userMain_explain));
		txt_explain.setTypeface(getFont());
		txt_subTitle.setTypeface(getFont());
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			gotoBack();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		dbAdapter.close();
		if (isUserWantToExit == true) {
			moveTaskToBack(true);
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		selectedNameID = -1;

		setExplainText(); // 설명 글에 사용자 이름을 표시한다.

		makeUserList(); // 사용자 목록을 불러온다
	}

	private void makeUserList() {

		// Cursor nameCursor = dbAdapter.getUserList(pref.getInt("ownerUID",
		// 1));
		Cursor nameCursor = dbAdapter.getUserList();
		listUser = new ArrayList<ArrayList<String>>();

		while (nameCursor.moveToNext()) {
			ArrayList<String> tempList = new ArrayList<String>();

			tempList.add(nameCursor.getString(0)); // user_name
			tempList.add(nameCursor.getString(1)); // user_gender
			tempList.add(nameCursor.getString(2)); // user_birthday
			tempList.add(nameCursor.getString(3)); // uid

			listUser.add(tempList);
		}

		listName = new ArrayList<TextView>();
		linear_userlist = (LinearLayout) findViewById(R.id.linear_nameList);
		linear_userlist.removeAllViews();

		ImageView tempLine = new ImageView(AC_UserMain.this);
		tempLine.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, convertDPtoPX(0.666)));
		tempLine.setBackgroundColor(Color.rgb(0x80, 0x80, 0x80));
		
		linear_userlist.addView(tempLine);
		
		for (int i = 0; i < listUser.size(); i++) {
			if (i == 0) {
				linear_userlist.addView(getNameTD(listUser.get(i).get(0),
						NAME_TOP, 1000 + i));
			} else if (0 < i && i < listUser.size() - 1) {
				linear_userlist.addView(getNameTD(listUser.get(i).get(0),
						NAME_MIDDLE, 1000 + i));
			} else {
				linear_userlist.addView(getNameTD(listUser.get(i).get(0),
						NAME_BOTTOM, 1000 + i));
			}
			
			tempLine = new ImageView(AC_UserMain.this);
			tempLine.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, convertDPtoPX(0.666)));
			tempLine.setBackgroundColor(Color.rgb(0x80, 0x80, 0x80));
			
			linear_userlist.addView(tempLine);
		}

				
		
		// TextView가 한 개 일 경우 배경을 한개 전용 배경으로 바꾼다.
		/*
		if (listUser.size() == 1) {
			linear_userlist.getChildAt(0).setBackgroundDrawable(
					getResources().getDrawable(R.drawable.background_edittext));
		}*/
	}

	private TextView getNameTD(String name, int position, int id) {
		@SuppressWarnings("unused")
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/MuseoSans_700.otf");

		int layout_width = 0;
		int layout_height = 0;
		Drawable background = getResources().getDrawable(
				R.drawable.c_btn_setting);
		
		layout_height = convertDPtoPX(56);
		
		TextView tv = new TextView(getApplicationContext());
		

		tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
				layout_height, Gravity.CENTER));
		tv.setBackgroundDrawable(background);
		tv.setGravity(Gravity.CENTER);
		
		// 현재 사용자면 이름을 굵게 표시한다.
		if (mSharedPreference.getUserName().equals(name)) {
			String s = "<b>" + name + "</b>";
			tv.setText(Html.fromHtml(s));
		} else {
			tv.setText(name);
		}
		
		tv.setTypeface(getFont());
		tv.setTextColor(Color.parseColor("#4c483f"));
		tv.setTextSize(convertDPtoPX(7.5));
		tv.setId(id);
		tv.setOnClickListener(onClickListener);

		listName.add(tv);
		return tv;
	}

	// Font 수정을 위한 Typeface를 가져온다.
	private Typeface getFont() {
		// Typeface tf = Typeface.createFromAsset(getAssets(),
		// "fonts/MuseoSans_700.otf");
		return Typeface.createFromAsset(getAssets(), "fonts/Daum_Regular.ttf");
	}

	private void registButtonEvents() {
		btn_TopLeft.setOnClickListener(onClickListener);
		btn_TopRight.setOnClickListener(onClickListener);

		tab_measure.setOnClickListener(onClickListener);
		tab_record.setOnClickListener(onClickListener);
		tab_help.setOnClickListener(onClickListener);

		btn_userChange.setOnClickListener(onClickListener);
		btn_userDelete.setOnClickListener(onClickListener);
		btn_userAdd.setOnClickListener(onClickListener);
	}

	private void gotoMeasure() {
		if (selectedNameID >= 0) {
			String user_name = listUser.get(selectedNameID).get(0);
			String user_gender = listUser.get(selectedNameID).get(1);
			String user_birthday = listUser.get(selectedNameID).get(2);
			String user_uid = listUser.get(selectedNameID).get(3);

			mSharedPreference.setUserName(user_name);
			mSharedPreference.setUserGender(user_gender);
			mSharedPreference.setUserBirthday(user_birthday);
			mSharedPreference.setUserUID(Integer.parseInt(user_uid));

			gotoBack();
		} else {
			Toast.makeText(AC_UserMain.this,
					getString(R.string.userMain_Please_Select_User), 1000)
					.show();
		}
	}

	private void gotoBack() {
		Intent intent = new Intent(AC_UserMain.this, AC_Scan_main.class);
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.fadein, R.anim.fadeout);
	}

	View.OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent;

			switch (v.getId()) {
			// ---------------------------------------
			case R.id.btn_top_left:
				gotoBack();
				break;
			// ---------------------------------------
			case R.id.btn_top_right:
				gotoMeasure();
				break;
			// ---------------------------------------
			// ---------------------------------------
			case R.id.btn_user_change:
				if (selectedNameID < 0) {
					// 사용자를 선택해야 한다고 경고
					Toast.makeText(
							AC_UserMain.this,
							getString(R.string.userMain_not_selected_user_change),
							1000).show();
				}

				else {
					intent = new Intent(AC_UserMain.this, AC_UserChange.class);
					intent.putExtra("user_uid", Integer.parseInt(listUser.get(
							selectedNameID).get(3)));
					startActivity(intent);
					overridePendingTransition(R.anim.fadein, R.anim.fadeout);
				}
				break;
			case R.id.btn_user_delete:
				if (selectedNameID >= 0) {

					if (selectedName.equals(mSharedPreference.getUserName())) {
						Toast.makeText(
								AC_UserMain.this,
								getString(R.string.userMain_current_user_delete),
								1000).show();
					} else {
						AlertDialog.Builder alert = new AlertDialog.Builder(
								AC_UserMain.this);
						alert.setTitle(getString(R.string.userMain_dialog_title_user_delete)
								+ " " + selectedName);
						alert.setMessage(getString(R.string.userMain_dialog_content_user_delete));
						alert.setNegativeButton(
								getString(R.string.dialog_Cancel),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});
						alert.setPositiveButton(
								getString(R.string.dialog_Delete),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										int uid_user = Integer
												.parseInt(listUser.get(
														selectedNameID).get(3));

										dbAdapter.deleteUser(uid_user);
										Toast.makeText(AC_UserMain.this,
												"Deleted", 1000).show();
										makeUserList();
									}
								});
						alert.show();
					}
				} else {
					Toast.makeText(AC_UserMain.this,
							getString(R.string.userMain_Please_Select_User),
							1000).show();
				}
				break;
			case R.id.btn_user_add:
				intent = new Intent(AC_UserMain.this, AC_UserAdd.class);
				startActivity(intent);
				overridePendingTransition(R.anim.fadein, R.anim.fadeout);
				break;
			// ---------------------------------------
			// ---------------------------------------
			case R.id.tab_measure:
				gotoBack();
				break;
			case R.id.tab_record:
				intent = new Intent(AC_UserMain.this, AC_RecordMain.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.fadein, R.anim.fadeout);
				break;
			case R.id.tab_help:
				intent = new Intent(AC_UserMain.this, AC_Help_main.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.fadein, R.anim.fadeout);
				break;
			}

			if (v.getId() > 999) {
				for (int i = 0; i < listName.size(); i++) {
					if (v.getId() == 1000 + i) {
						selectedName = listName.get(i).getText().toString();
						long nowClickedNameTime = new Date().getTime();

						if (selectedNameID == i
								&& nowClickedNameTime - lastClickedNameTime < doubleClickTime) {
							// 같은 이름이 두번 선택되면 측정 화면으로 이동한다.
							gotoMeasure();
						} else {
							selectedNameID = i;
							lastClickedNameTime = nowClickedNameTime;
						}
						//listName.get(i).setTextColor(Color.parseColor("#9E0E10"));
						listName.get(i).setBackgroundDrawable(getResources().getDrawable(R.drawable.background_setting_1));
					} else {
						//listName.get(i).setTextColor(Color.parseColor("#4c483f"));
						listName.get(i).setBackgroundDrawable(getResources().getDrawable(R.drawable.c_btn_setting));
					}
				}
			}
		}
	};

	@SuppressWarnings("unused")
	private void changeFont() {
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/MuseoSans_700.otf");

		// txt_userName.setTypeface(tf);
	}

	private int convertDPtoPX(double dp) {
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

		return (int) (dp * outMetrics.density + 0.5f);
	}
}
